package com.ahaoyou.atomic;


import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

/**
 * @Author LH
 * @create 2021/12/22 14:25
 */
public class TestAsync {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        testAsync();
        testNoAsync();
    }

    public static void testAsync() throws ExecutionException, InterruptedException {
        long startTime = System.currentTimeMillis();
        List<CompletableFuture<Integer>> completableFutures = new ArrayList<>(10);
        for (int i = 0; i < 6; i++) {
            int k = i;
            CompletableFuture<Integer> result = CompletableFuture.supplyAsync(() -> {
                try {
                    Thread.sleep(1000);
                    return k;
                } catch (InterruptedException e) {
                    return 0;
                }
            });
            completableFutures.add(result);
        }
        CompletableFuture.allOf(completableFutures.toArray(new CompletableFuture[completableFutures.size()])).join();
        List<Integer> list = new ArrayList<>();
        for (CompletableFuture<Integer> completableFuture : completableFutures) {
            list.add(completableFuture.get());
        }
        long endTime = System.currentTimeMillis();
        System.out.println("异步结果" + list);
        System.out.println("异步消费时间" + (endTime - startTime));
    }

    public static void testNoAsync() throws InterruptedException {
        long startTime = System.currentTimeMillis();
        List<Integer> list = new ArrayList<>();
        for (int i = 0; i < 6; i++) {
            Thread.sleep(1000);
            list.add(i);
        }
        long endTime = System.currentTimeMillis();
        System.out.println("同步结果" + list);
        System.out.println("同步消费时间" + (endTime - startTime));
    }
}
